package cn.dianchiyun.protocol.netty.dtu;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 基站与对应的会话的管理器
 * @version 1.0
 * @author: weir
 * @date: 2019/3/7 4:40 PM
 */
public class ChannelManager {

    private Logger logger = LoggerFactory.getLogger(ChannelManager.class);

    /** 缓存基站与对应的会话 */
    private ConcurrentMap<String, Channel> siteCode2Channel = new ConcurrentHashMap<>();

    /** 缓存会话Id与基站的对应关系 */
    private ConcurrentMap<String, String> channelId2siteCode = new ConcurrentHashMap<>();

    private final static ChannelManager INSTANCE = new ChannelManager();

    private ChannelManager(){}

    public static ChannelManager getInstance(){
        return INSTANCE;
    }

    public boolean isNotEmpty(String siteCode){
        return siteCode2Channel.containsKey(siteCode);
    }

    /**
     * 增加
     * @param siteCode
     * @param channel
     */
    public void addChannel(String siteCode, Channel channel){
        siteCode2Channel.put(siteCode, channel);
        channelId2siteCode.put(channel.id().asLongText(), siteCode);
    }

    /**
     * 移除
     * @param channel
     */
    public void remove(Channel channel){
        String id  = channel.id().asLongText();
        if(channelId2siteCode.containsKey(id)){
            String siteCode = channelId2siteCode.get(id);
            if(siteCode2Channel.containsKey(siteCode)) {
                siteCode2Channel.remove(siteCode);
            }
            channelId2siteCode.remove(id);
        }
    }

    /**
     * 对基站发送数据
     * @param siteCode
     * @param pact
     */
    public boolean sendMsgTo(String siteCode, final String pact){
        if(pact == null || StringUtils.isEmpty(siteCode)) {
            return false;
        }
        Channel channel = siteCode2Channel.get(siteCode);
        if (channel != null) {
            logger.info("channelId:{}" + channel.id().asLongText());
            logger.info("channelId:{}" + channel.isActive() + "----" + channel.isWritable());
            ChannelFuture channelFuture = channel.writeAndFlush(pact);
            final boolean suc = false;
            /*channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    logger.info(pact+"----"+future.isSuccess()+"");
                }
            });*/
            return true;
        }else{
            return false;
        }
    }

    public ConcurrentMap<String, Channel> getSiteCode2Channel() {
        return siteCode2Channel;
    }
}
